<template>
  <div class="btn_style">
    <div>
      <ArcoButton type="primary" size="mini" @click="testEdit">
        <template #icon>
          <icon-plus />
        </template>
        历史记录
      </ArcoButton>
      <ArcoButton size="mini" status="warning" @click="handleClick2">
        <template #icon>
          <icon-plus />
        </template>
        执行全部
      </ArcoButton>
      <ArcoButton size="mini" status="success" @click="executeSelectedQuery">
        <template #icon>
          <icon-plus />
        </template>
        执行选中
      </ArcoButton>
      <!--      <a-select-->
      <!--        v-model:value="thisDb"-->
      <!--        size="small"-->
      <!--        style="width: 150px"-->
      <!--        :options="databaseList"-->
      <!--      ></a-select>-->
      <a-tag color="#55acee" style="margin-left: 30px">
        <template #icon>
          <DatabaseOutlined />
        </template>
        当前数据库: {{ thisDb }}
      </a-tag>
    </div>
    <div>
      <ArcoButton size="mini" status="warning" disabled>
        <template #icon>
          <icon-plus />
        </template>
        执行耗时：12ms
      </ArcoButton>
    </div>
  </div>
  <div style="height: 100%">
    <ArcoSplit
      v-model:size="splitSize"
      direction="vertical"
      :style="{
        height: '100%',
        width: '100%',
        border: '1px solid var(--color-border)'
      }"
    >
      <template #first>
        <div ref="editorContainer" class="monaco-editor-container"></div>
      </template>
      <template #second>
        <div style="height: 100%">
          <a-table
            :columns="columns"
            :data-source="data"
            :pagination="{ pageSize: 50 }"
            :scroll="{ y: 350 }"
          />
        </div>
      </template>
    </ArcoSplit>
  </div>
</template>

<script setup>
import * as monaco from 'monaco-editor'
import { ref, onMounted, watch } from 'vue'
import { Split as ArcoSplit, Button as ArcoButton } from '@arco-design/web-vue'
import { message as SystemMsg } from 'ant-design-vue/es/components'
import { DatabaseOutlined } from '@ant-design/icons-vue'

const { ipcRenderer } = window.electron
const thisConnect = ref(null)
const thisDb = ref('')
const databaseList = ref([])
// Editor ref
const editorContainer = ref(null)
let editor = null

//执行选中SQL
const executeSelectedQuery = async () => {
  if (editor) {
    const selection = editor.getSelection()
    if (selection && !selection.isEmpty()) {
      const selectedText = editor.getModel().getValueInRange(selection)

      // 调用 IPC 或 API 发送 selectedText 到服务端执行
      const res = await ipcRenderer.invoke('doQuery', selectedText)
      alert(res)
    } else {
      alert('请先选择需要执行的 SQL 片段')
    }
  }
}

//获取本地以及当前连接信息
// const getLocalConnectAndThisConnect = async () => {
//   let sql = `SHOW DATABASES;`
//   const res = await ipcRenderer.invoke('getConnInfo')
//   if (!res) {
//     const connList = await ipcRenderer.invoke('getValue', 'connList')
//     if (!connList) {
//       SystemMsg.error('请先添加连接')
//     } else {
//       const list = JSON.parse(connList)
//       await ipcRenderer.invoke('connectToTDengine', JSON.stringify(list[0]))
//     }
//   }
//   const sqlRes = await ipcRenderer.invoke('doQuery', sql)
//   databaseList.value = []
//   sqlRes.forEach((item) => {
//     databaseList.value.push({
//       value: item[0],
//       label: item[0]
//     })
//   })
//   const database = await ipcRenderer.invoke('getValue', 'thisDatabase')
//   console.log(database, 'database')
//   thisDb.value = database.title
//   console.log(databaseList.value, 'databaseList.value')
// }
const getLocalConnectAndThisConnect = async () => {
  try {
    // 1. 获取连接信息
    const res = await ipcRenderer.invoke('getConnInfo')
    if (!res) {
      const connList = await ipcRenderer.invoke('getValue', 'connList')
      if (!connList) {
        SystemMsg.error('请先添加连接')
        return
      }

      const list = JSON.parse(connList)
      if (list.length === 0) {
        SystemMsg.error('连接列表为空')
        return
      }

      await ipcRenderer.invoke('connectToTDengine', JSON.stringify(list[0]))
    }

    SystemMsg.info(res)
    // 2. 获取数据库列表
    const sqlRes = await ipcRenderer.invoke('doQuery', 'SHOW DATABASES;')
    databaseList.value = sqlRes.map(item => ({
      value: item[0],
      label: item[0]
    }))

    // 3. 获取当前数据库
    const database = await ipcRenderer.invoke('getValue', 'thisDatabase')
    console.log('原始数据库数据:', database) // 调试日志

    if (database) {
      try {
        const dbData = JSON.parse(database)
        thisDb.value = dbData.title || dbData.database || ''
      } catch (e) {
        // 如果不是JSON，直接使用原始值
        thisDb.value = database
      }
    } else {
      SystemMsg.warning('未获取到当前数据库信息')
    }

    console.log('当前数据库:', thisDb.value) // 调试日志
  } catch (error) {
    console.error('获取连接和数据库信息失败:', error)
    SystemMsg.error(`获取信息失败: ${error.message}`)
  }
}

// State
const cursorPosition = ref({ line: 1, column: 1 })
const theme = ref('vs-dark')
const splitSize = ref(0.8)
const initialSql = ref()

const file = ref({
  name: 'query.sql',
  saved: true
})

const testEdit = () => {
  if (editor) {
    editor.setValue('-- 测试写入\nSELECT * FROM test_table;')
  }
}

// Initialize Monaco Editor
onMounted(() => {
  if (editorContainer.value) {
    editor = monaco.editor.create(editorContainer.value, {
      value: initialSql.value,
      language: 'sql',
      theme: 'Dark',
      automaticLayout: true,
      minimap: {
        enabled: true
      },
      scrollbar: { vertical: 'hidden' }, //滚动条
      scrollBeyondLastLine: false,
      fontSize: 14,
      lineNumbers: 'on',
      roundedSelection: true,
      scrollBeyondLastColumn: 5,
      readOnly: false,
      contextmenu: true,
      formatOnPaste: true,
      formatOnType: true
    })

    // 添加调试信息
    console.log('当前模型:', editor.getModel())
    console.log('是否只读:', editor.getOption(monaco.editor.EditorOption.readOnly))

    // Handle content changes
    editor.onDidChangeModelContent(() => {
      file.value.saved = false
    })

    // Handle cursor position changes
    editor.onDidChangeCursorPosition((e) => {
      cursorPosition.value = {
        line: e.position.lineNumber,
        column: e.position.column
      }
    })
  }
})

// Watch theme changes
watch(theme, (newTheme) => {
  if (editor) {
    monaco.editor.setTheme(newTheme)
  }
})

// Methods
const formatCode = () => {
  if (editor) {
    editor.getAction('editor.action.formatDocument').run()
  }
}

const executeQuery = () => {
  const query = editor ? editor.getValue() : ''
  alert('执行查询: ' + query.substring(0, 100) + (query.length > 100 ? '...' : ''))
}

const saveQuery = () => {
  file.value.saved = true
  alert('保存成功!')
}

const newQuery = () => {
  if (editor) {
    editor.setValue('-- 新查询\nSELECT * FROM table_name;')
    file.value = {
      name: 'new_query.sql',
      saved: false
    }
  }
}

const setTheme = (newTheme) => {
  theme.value = newTheme
}

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    width: 150
  },
  {
    title: 'Age',
    dataIndex: 'age',
    width: 150
  },
  {
    title: 'Address',
    dataIndex: 'address'
  }
]

const data = [...Array(100)].map((_, i) => ({
  key: i,
  name: `Edward King ${i}`,
  age: 32,
  address: `London, Park Lane no. ${i}`
}))

onMounted(() => {
  getLocalConnectAndThisConnect()
})
</script>

<style scoped>
.monaco-editor-container {
  height: 100%;
  width: 100%;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.arco-split-trigger-icon) {
  margin: -4px;
}

:deep(.arco-split-trigger-icon-wrapper svg) {
  visibility: hidden;
}

.btn_style {
  display: flex;
  justify-content: space-between;
}
</style>
